/// @Author wywinstonwy
/// @Date 2022/1/18 8:13 上午
/// @Description: 
import 'package:demo202112/utils/common_appbar.dart';
import "package:flutter/material.dart";

class KeepAliveWrapper extends StatefulWidget {
  final bool keepAlive;
  final Widget child;

  const KeepAliveWrapper({
    Key? key,
    this.keepAlive = true,
    required this.child,
  }) : super(key: key);



  @override
  _KeepAliveWrapperState createState() => _KeepAliveWrapperState();
}

class _KeepAliveWrapperState extends State<KeepAliveWrapper>
    with AutomaticKeepAliveClientMixin {
  @override
  Widget build(BuildContext context) {
    super.build(context);
    print("build ${widget.child}");
    return widget.child;
  }

  @override
  void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
    if(oldWidget.keepAlive != widget.keepAlive) {
      // keepAlive 状态需要更新，实现在 AutomaticKeepAliveClientMixin 中
      updateKeepAlive();
    }
    super.didUpdateWidget(oldWidget);
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
}

class WyPageViewAlive extends StatefulWidget {
  const WyPageViewAlive({Key? key}) : super(key: key);

  @override
  _WyPageViewAliveState createState() => _WyPageViewAliveState();
}

class _WyPageViewAliveState extends State<WyPageViewAlive> {
  List <Widget> children = [];
  
  @override
  Widget build(BuildContext context) {
    for(int i=0;i<10;i++){
      children.add((KeepAliveWrapper(child: Center(child: Text(' $i',textScaleFactor: 5,),))));
    }
    return Scaffold(
      appBar: getAppBar('页面缓存'),
      body: PageView(children: children),);
  }
}
